

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="深海火锅店">
  <meta name="keywords" content="">
  
    <meta name="description" content="聚合函数作为窗口函数在窗口中每条记录动态地应用聚合函数( SUM()、AVG()、MAX()、MIN()、COUNT() )，可以动态计算在指定的窗口内的各种聚合函数值。用来作为滑动窗口使用。 作用：聚合函数作为窗口函数，是起到”累加&#x2F;累计”的效果，比如，就是截止到本行，最大值、最小值是多少与专用窗口函数的区别：括号中需要有指定列，不能为空用法：聚合函数名(字段名)OVER(PARTIO">
<meta property="og:type" content="article">
<meta property="og:title" content="DB18_分析函数2-窗口函数">
<meta property="og:url" content="http://example.com/2022/12/29/%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/%E5%A4%A7%E6%95%B0%E6%8D%AE%E5%AD%A6%E4%B9%A0/DB18&DB19/DB18_%E5%88%86%E6%9E%90%E5%87%BD%E6%95%B02-%E7%AA%97%E5%8F%A3%E8%81%9A%E5%90%88%E5%87%BD%E6%95%B0%20copy/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="聚合函数作为窗口函数在窗口中每条记录动态地应用聚合函数( SUM()、AVG()、MAX()、MIN()、COUNT() )，可以动态计算在指定的窗口内的各种聚合函数值。用来作为滑动窗口使用。 作用：聚合函数作为窗口函数，是起到”累加&#x2F;累计”的效果，比如，就是截止到本行，最大值、最小值是多少与专用窗口函数的区别：括号中需要有指定列，不能为空用法：聚合函数名(字段名)OVER(PARTIO">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-12-29T01:00:00.000Z">
<meta property="article:modified_time" content="2022-12-31T11:41:08.000Z">
<meta property="article:author" content="深海火锅店">
<meta property="article:tag" content="大数据">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>DB18_分析函数2-窗口函数 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fluid</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/background.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="DB18_分析函数2-窗口函数"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-12-29 09:00" pubdate>
          2022年12月29日 上午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          3.7k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          31 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">DB18_分析函数2-窗口函数</h1>
            
            
              <div class="markdown-body">
                
                <h3 id="聚合函数作为窗口函数"><a href="#聚合函数作为窗口函数" class="headerlink" title="聚合函数作为窗口函数"></a>聚合函数作为窗口函数</h3><p>在窗口中每条记录动态地应用聚合函数( SUM()、AVG()、MAX()、MIN()、COUNT() )，可以动态计算在指定的窗口内的各种<br>聚合函数值。用来作为滑动窗口使用。</p>
<p><strong>作用：</strong><br>聚合函数作为窗口函数，是起到”累加&#x2F;累计”的效果，比如，就是截止到本行，最大值、最小值是多少<br><strong>与专用窗口函数的区别：</strong><br>括号中需要有指定列，不能为空<br><strong>用法：</strong><br>聚合函数名(字段名)OVER(PARTION BY 字段名ORDER BY字段名)</p>
<h3 id="AVG作为窗口函数"><a href="#AVG作为窗口函数" class="headerlink" title="AVG作为窗口函数"></a>AVG作为窗口函数</h3><p><strong>语法：</strong><br>AVG(字段名)OVER(PARTION BY 字段名ORDER BY 字段名)<br><strong>案例</strong><br>查找单科成绩高于该科目平均成绩的学生名单，考虑</p>
<ul>
<li>单科成绩，表示需要按科目进行分组，分组有两种:GROUP BY子句和窗口函数的PARTITION BY</li>
<li>要求平均值，需要通过AVG()实现，并且找到大于平均值的学生，那么不能减少行数，则用PARTITION BY</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs sql"># 方法一：<br><span class="hljs-keyword">select</span> student_id, course_id, score<br><span class="hljs-keyword">from</span> sales.t_scores <span class="hljs-keyword">as</span> t1<br><span class="hljs-keyword">where</span> t1.score <span class="hljs-operator">&gt;</span> (<span class="hljs-keyword">select</span> <span class="hljs-built_in">avg</span>(t2.score) <span class="hljs-keyword">as</span> avg_score<br>                  <span class="hljs-keyword">from</span> sales.t_scores <span class="hljs-keyword">as</span> t2<br>                  <span class="hljs-keyword">where</span> t1.course_id <span class="hljs-operator">=</span> t2.course_id);<br><br># 方法二：<br><span class="hljs-keyword">SELECT</span> <span class="hljs-operator">*</span><br><span class="hljs-keyword">FROM</span> (<span class="hljs-keyword">SELECT</span> student_id,<br>             course_id,<br>             score,<br>             <span class="hljs-built_in">AVG</span>(score) <span class="hljs-keyword">OVER</span> w <span class="hljs-keyword">As</span> avg_score<br>      <span class="hljs-keyword">FROM</span> sales.t_scores <span class="hljs-keyword">AS</span> t1<br>          <span class="hljs-keyword">WINDOW</span> w <span class="hljs-keyword">AS</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> course_id)) <span class="hljs-keyword">AS</span> t1<br><span class="hljs-keyword">WHERE</span> t1.score <span class="hljs-operator">&gt;</span> t1.avg_score;<br></code></pre></td></tr></table></figure>
<h4 id="实现移动平均"><a href="#实现移动平均" class="headerlink" title="实现移动平均"></a>实现移动平均</h4><p><strong>语法</strong><br>AVG(字段名)OVER(ORDER BY 字段名ROWS BETWEEN一个时间点 AND一个时间点)<br>时间点的取值有</p>
<ul>
<li>n PRECEDING:前n行 n FOLLOWING:后n行 CURRENT ROW :当前行</li>
<li>UNBOUNDED PRECEDING:窗口第一行</li>
<li>UNBOUNDED FOLLOWING:窗口的最后一行<br><strong>注意事项</strong><br>窗口函数中的如果省略PARTITION BY，则纪术个进1力lAeI 不进行排序;<br><strong>用法</strong><br>计算指定时间的平均销售额，可以拿学生成绩表进行模拟<br>SELECT student_id,course_id,score,<br>AVG(score) OVER w AS avg_scoreFROM sales.t_scores AS t1<br>WHERE t1.student_id &#x3D; ‘220102’WINDow w<br>AS (PARTITION BY student_id ORDER BY course_id <font style="color: red">ROWS 2 PRECEDING</font>);<br><font style="color: red">参数ROWS N PROCEDING</font><br>N表示在当前行的前N行，比如，N&#x3D;2，当前行在第4行，那么该平均值是第2行，第3行，第4行，这三行数据的平均值，则avg_score&#x3D;(99+87+91)&#x2F;3 &#x3D; 92.333</li>
</ul>
<h3 id="MIN作为窗口函数"><a href="#MIN作为窗口函数" class="headerlink" title="MIN作为窗口函数"></a>MIN作为窗口函数</h3><p><strong>语法</strong><br>MIN(字段名)OVER(PARTION BY 字段名)，注意不需要使用ORDER BY<br><strong>案例</strong><br>在一个查询实现不同的最低分与自己的分数进行比较，比较差距。</p>
<ul>
<li>每个学生的最低分</li>
<li>每门课程的最低分<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> student_id,course_id,score,<br><span class="hljs-built_in">MIN</span>(score) <span class="hljs-keyword">OVER</span> w1 <span class="hljs-keyword">AS</span> course_min_score,<span class="hljs-built_in">MIN</span>(score) <span class="hljs-keyword">OVER</span> w2 <span class="hljs-keyword">AS</span> student_min_sore<br><span class="hljs-keyword">FROM</span> sales.t_scores t1<br><span class="hljs-keyword">WINDOw</span> w1 <span class="hljs-keyword">AS</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> t1.course_id),w2 <span class="hljs-keyword">AS</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> t1.student_id)<br>LIMIT <span class="hljs-number">12</span>;<br></code></pre></td></tr></table></figure></li>
</ul>
<h3 id="窗口函数案例应用"><a href="#窗口函数案例应用" class="headerlink" title="窗口函数案例应用"></a>窗口函数案例应用</h3><p>在一个查询实现每个学生的最低最高分析，所有学生范围的最高最低分<br><strong>思路</strong></p>
<ul>
<li>每个学生的最低最高，使用PARTITION BY student_id定义窗口</li>
<li>所有学生范围的最低最高，不指定范围则表示全部数据<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">distinct</span> student_id,<br><span class="hljs-built_in">MIN</span>(score) <span class="hljs-keyword">OVER</span> w1 <span class="hljs-keyword">AS</span> student_min_score,<br><span class="hljs-built_in">MAX</span>(score) <span class="hljs-keyword">OVER</span> w1 <span class="hljs-keyword">AS</span> student_max_score,<br><span class="hljs-built_in">MIN</span>(score) <span class="hljs-keyword">OVER</span> w2 <span class="hljs-keyword">AS</span> all_min_score,<br><span class="hljs-built_in">MAX</span>(score) <span class="hljs-keyword">OVER</span> w2 <span class="hljs-keyword">AS</span> all_max_scoreFROM sales.t_scores t1<br><span class="hljs-keyword">WINDOW</span> w1 <span class="hljs-keyword">AS</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> t1.student_id),w2 <span class="hljs-keyword">AS</span> ();<br></code></pre></td></tr></table></figure></li>
</ul>
<p>系统存储有(游戏)用户登录表user_login，模拟数据如下</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> sales.user_login(<br>user_name <span class="hljs-type">VARCHAR</span>( <span class="hljs-number">5</span> ),<br>login_dt <span class="hljs-type">date</span>);<br><br><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> sales.user_login<br><span class="hljs-keyword">VALUES</span><br>(<span class="hljs-string">&#x27;A&#x27;</span>, <span class="hljs-string">&#x27;2020/8/1&#x27;</span>),(<span class="hljs-string">&#x27;B&#x27;</span>,<span class="hljs-string">&#x27;2020/8/2&#x27;</span>),(<span class="hljs-string">&#x27;A&#x27;</span>, <span class="hljs-string">&#x27;2020/8/2&#x27;</span>),(<span class="hljs-string">&#x27;C&#x27;</span>,<span class="hljs-string">&#x27;2020/8/3&#x27;</span>),<br>(<span class="hljs-string">&#x27;A&#x27;</span>, <span class="hljs-string">&#x27;2020/8/3&#x27;</span>),(<span class="hljs-string">&#x27;D&#x27;</span>,<span class="hljs-string">&#x27;2020/8/4&#x27;</span>),(<span class="hljs-string">&#x27;C&#x27;</span>, <span class="hljs-string">&#x27;2020/8/4&#x27;</span>),(<span class="hljs-string">&#x27;B&#x27;</span>,<span class="hljs-string">&#x27;2020/8/4&#x27;</span>),<br>(<span class="hljs-string">&#x27;A&#x27;</span>, <span class="hljs-string">&#x27;2020/8/4&#x27;</span>),(<span class="hljs-string">&#x27;A&#x27;</span>,<span class="hljs-string">&#x27;2020/8/5&#x27;</span>),(<span class="hljs-string">&#x27;B&#x27;</span>, <span class="hljs-string">&#x27;2020/8/5&#x27;</span>),(<span class="hljs-string">&#x27;C&#x27;</span>,<span class="hljs-string">&#x27;2020/8/6&#x27;</span>),<br>(<span class="hljs-string">&#x27;A&#x27;</span>, <span class="hljs-string">&#x27;2020/8/6&#x27;</span>),(<span class="hljs-string">&#x27;A&#x27;</span>,<span class="hljs-string">&#x27;2020/8/7&#x27;</span>),(<span class="hljs-string">&#x27;A&#x27;</span>, <span class="hljs-string">&#x27;2020/8/8&#x27;</span>),(<span class="hljs-string">&#x27;B&#x27;</span>,<span class="hljs-string">&#x27;2020/8/9&#x27;</span>);<br></code></pre></td></tr></table></figure>
<p>求连续7天都登录平台的重要用户，思路</p>
<ul>
<li>利用LEAD函数查询每个用户后7条记录，如果有则返回相应日期，如果无则返回NULL</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> user_name,<br>login_dt,<br><span class="hljs-built_in">LEAD</span>(login_dt, <span class="hljs-number">7</span>) <span class="hljs-keyword">OVER</span> w <span class="hljs-keyword">AS</span> dt7<br><span class="hljs-keyword">FROM</span> sales.user_login<br><span class="hljs-keyword">WINDOW</span> w <span class="hljs-keyword">AS</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> user_name <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> login_dt)<br></code></pre></td></tr></table></figure>
<ul>
<li>查询用户登录时间往后推七天的日期，判断LEAD和前天后的日期是否相等<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> user_name<br><span class="hljs-keyword">FROM</span> t1 <span class="hljs-comment">--t1为第一步封装的子查询</span><br><span class="hljs-keyword">WHERE</span> t1.dt7 <span class="hljs-keyword">IS</span> <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">NULL</span><br><span class="hljs-keyword">AND</span> DATE_ADD(login_dt, <span class="hljs-type">INTERVAL</span> <span class="hljs-number">7</span> <span class="hljs-keyword">DAY</span>) <span class="hljs-operator">=</span> dt7<br></code></pre></td></tr></table></figure></li>
</ul>
<p>求商品种类的按照月份统计的环比和同比数据，计算环比增长率和同比增长率。<br><strong>思路如下</strong></p>
<ul>
<li>先对原始数据按照月份进行统计形成子查询t2</li>
<li>基于t2使用PARTITION BY商品种类形成窗口，窗口数据按照订单月份进行升序排序</li>
<li>使用LAG窗口往前1行获取上月销售数据，往前推12个月获取同期销售</li>
<li>列间计算环比增长率和同比增长率<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> t2.ord_month <span class="hljs-keyword">AS</span>销售月份.<br>t2.prod_category <span class="hljs-keyword">AS</span>商品类别,<br>t2.sold_quantity <span class="hljs-keyword">AS</span>销售数量，<br><span class="hljs-built_in">LAG</span>(t2.sold_quantity,<span class="hljs-number">1</span>)   <span class="hljs-keyword">OVER</span> w <span class="hljs-keyword">AS</span> 环比数量,<br><span class="hljs-built_in">LAG</span>(t2.sold_quantity, <span class="hljs-number">12</span>) <span class="hljs-keyword">OVER</span> w <span class="hljs-keyword">AS</span> 同比数量,<br>(t2.sold_quantity <span class="hljs-operator">-</span> <span class="hljs-built_in">LAG</span>(t2.sold_quantity,<span class="hljs-number">1</span>)  <span class="hljs-keyword">OVER</span> w)<br><span class="hljs-operator">/</span><span class="hljs-built_in">LAG</span>(t2.sold_quantity, <span class="hljs-number">1</span>) <span class="hljs-keyword">OVER</span> w <span class="hljs-keyword">AS</span> 同比增长率,<br>(t2.sold_quantity <span class="hljs-operator">-</span> <span class="hljs-built_in">LAG</span>(t2.sold_quantity,<span class="hljs-number">12</span>) <span class="hljs-keyword">OVER</span> w)<br><span class="hljs-operator">/</span><span class="hljs-built_in">LAG</span>(t2.sold_quantity, <span class="hljs-number">12</span>)<span class="hljs-keyword">OVER</span> w <span class="hljs-keyword">AS</span> 环比增长率<br><span class="hljs-keyword">FROM</span>(<br><span class="hljs-keyword">SELECT</span> DATE_FORMAT(t1.orderdate, <span class="hljs-string">&#x27;%Y-%m&#x27;</span>) <span class="hljs-keyword">AS</span> ord_month,<br>t1.categoryname <span class="hljs-keyword">AS</span> prod_category,<br><span class="hljs-built_in">SUM</span>(t1.quantity) <span class="hljs-keyword">AS</span> sold_quantity<br><span class="hljs-keyword">FROM</span> northwind.sales t1<br><span class="hljs-keyword">WHERE</span> t1.categoryname <span class="hljs-operator">=</span> <span class="hljs-string">&#x27;点心&#x27;</span> <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> prod_category,ord_month) <span class="hljs-keyword">AS</span> t2<br><span class="hljs-keyword">WINDOW</span> w <span class="hljs-keyword">AS</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> t2.prod_category <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> t2.ord_month);<br></code></pre></td></tr></table></figure></li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%A4%A7%E6%95%B0%E6%8D%AE/" class="category-chain-item">大数据</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E5%A4%A7%E6%95%B0%E6%8D%AE/">#大数据</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>DB18_分析函数2-窗口函数</div>
      <div>http://example.com/2022/12/29/数据库/MySQL/大数据学习/DB18&amp;DB19/DB18_分析函数2-窗口聚合函数 copy/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>深海火锅店</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年12月29日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/12/29/%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/%E5%A4%A7%E6%95%B0%E6%8D%AE%E5%AD%A6%E4%B9%A0/DB18&amp;DB19/DB19_%E5%AD%98%E5%82%A8%E8%BF%87%E7%A8%8B1/" title="DB19_存储过程1">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">DB19_存储过程1</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/12/28/%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/%E5%A4%A7%E6%95%B0%E6%8D%AE%E5%AD%A6%E4%B9%A0/DB16&amp;DB17/DB17_%E5%88%86%E6%9E%90%E5%87%BD%E6%95%B01-%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/" title="DB17_分析函数1-窗口函数">
                        <span class="hidden-mobile">DB17_分析函数1-窗口函数</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="//cdn.jsdelivr.net/gh/EmoryHuang/BlogBeautify@1.1/DynamicRibbon.min.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
